package com.ayu.wxgzh.ayucyy.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ayu.wxgzh.ayucyy.Utils.ChatGPTHttpUtil;
import com.ayu.wxgzh.ayucyy.entity.chatgpt.ImageResponseBody;
import com.ayu.wxgzh.ayucyy.entity.chatgpt.ImageSendBody;
import com.ayu.wxgzh.ayucyy.entity.chatgpt.MessageResponseBody;
import com.ayu.wxgzh.ayucyy.entity.chatgpt.MessageSendBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author 徐林玉
 * @Description ChatGPTServcie
 * @Date 2023/2/6 10:23
 * @Version 1.0
 */
@Service
@Slf4j
public class ChatGPTService {


    @Value("${chat.keys:}")
    private String apiKeys;

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 接口请求地址
     */
    private final String chatUrl = "https://api.openai.com/v1/completions";
    private final String genImageUrl = "https://api.openai.com/v1/images/generations";

    @Autowired
    public ChatGPTService(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 调用openAI的接口获取回复
     *
     * @param messageContent 用户发送的消息
     * @param fromUser       用户id
     * @return String
     */
    public String reply(String messageContent, String fromUser) {
        // 默认信息
        String message = "";
        //把msgcontent和fromuser转换成md5作为rediskey
        String contentPre = messageContent + "_" + fromUser;
        String md5Content = DigestUtils.md5DigestAsHex(contentPre.getBytes());
        // 如果存在key，拿出来
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(md5Content))) {

            message = stringRedisTemplate.opsForValue().get(md5Content);
            return message;

        }

        String body = "";
        String url = "";

        if (messageContent.length() > 4) {
            String keyword = messageContent.substring(0, 4);
            if ("draw".equalsIgnoreCase(keyword)) {
                //生成图片
                url = this.genImageUrl;
                int length = messageContent.length();
                String subContent = messageContent.substring(4, length);
                body = buildImageConfig(subContent);
                // 调用接口获取数据
                String obj = getChatReply(url, body);

                ImageResponseBody imageResponseBody = JSONObject.parseObject(obj, ImageResponseBody.class);
                if (imageResponseBody != null) {
                    if (!CollectionUtils.isEmpty(imageResponseBody.getData())) {
                        String imageurl = imageResponseBody.getData().get(0).getUrl();
                        message = "图片已生成，<a href=\"" + imageurl + "\">点击这里</a>查看";
                        //保存到redis里面
                        stringRedisTemplate.opsForValue().set(md5Content, message, 5, TimeUnit.MINUTES);
                        return message;
                    }
                }
            }
        }

        url = this.chatUrl;
        body = buildConfig(messageContent);
        // 调用接口获取数据
        String obj = getChatReply(url, body);
        MessageResponseBody messageResponseBody = JSONObject.parseObject(obj, MessageResponseBody.class);
        // 存储对话内容
        if (messageResponseBody != null) {
            if (!CollectionUtils.isEmpty(messageResponseBody.getChoices())) {
                String messagepre = messageResponseBody.getChoices().get(0).getText();
                message = messagepre.replaceFirst("[\r\n]+", "");
                //保存到redis里面
                stringRedisTemplate.opsForValue().set(md5Content, message, 5, TimeUnit.MINUTES);
            }
        }

        return message;

    }

    private String getChatReply(String url, String body) {


        Map<String, String> header = new HashMap();
        header.put("Authorization", "Bearer " + apiKeys);
        header.put("Content-Type", "application/json");
        // 发送请求
        String data = ChatGPTHttpUtil.hutoolPost(url, body, header);

        return data;

    }


    /**
     * 构建请求体
     *
     * @return
     */
    private String buildConfig(String prompt) {
        MessageSendBody messageSendBody = new MessageSendBody();
        messageSendBody.setModel("text-davinci-003");
        messageSendBody.setTemperature(0.9);
        messageSendBody.setMaxTokens(1000);
        messageSendBody.setTopP(1);
        messageSendBody.setFrequencyPenalty(0.0);
        messageSendBody.setPresencePenalty(0.6);
        messageSendBody.setPrompt(prompt);
        List<String> stop = new ArrayList<>();
        stop.add(" ayu:");
        stop.add(" Human:");
        messageSendBody.setStop(stop);
        String res = JSON.toJSONString(messageSendBody, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
        return res;
    }


    private String buildImageConfig(String prompt) {
        ImageSendBody imageSendBody = new ImageSendBody();
        imageSendBody.setPrompt(prompt);
        String res = JSON.toJSONString(imageSendBody, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);

        return res;
    }




}
